import express from 'express'
import {addSql, countSql, deleteSql, getResult, listSql, putSql} from '../../../util/operateSql.js';
var router = express.Router();
const table1 = 'sys_role'
const table2 = 'sys_role_menu'
const table3 = 'sys_menu'

router.get('/query', async function(req, res, next) {
  const sql = listSql(table1,{...req.query,orderBy: 'role_id'})
  const sql2 = countSql(table1, {...req.query,orderBy: 'role_id'})
	const resp1 = await getResult(sql)
	const resp2 = await getResult(sql2)
  res.json(req.app.locals.success({list: resp1,total: resp2[0].count}))
});
router.get('/list', async function(req, res, next) {
  const sql = listSql(table1,{...req.query,orderBy: 'role_id'},{hasPage:false})
	const resp1 = await getResult(sql)
  res.json(req.app.locals.success(resp1))
});
/* GET users listing. */
router.post('/add', function(req, res, next) {
  const sql = addSql(table1,{...req.body})
  getResult(sql).then((result) => {
    res.json(req.app.locals.success(result))
  }).catch((err) => {
    res.json(req.app.locals.error(err))
  });
});
router.post('/update', function(req, res, next) {
  const sql = putSql(table1,{...req.body},{role_id: req.body.role_id})
  getResult(sql).then((result) => {
    res.json(req.app.locals.success('修改成功'))
  }).catch((err) => {
    res.json(req.app.locals.error(err))
  });
});

// 角色分配权限
router.post('/dataScope', async function(req, res, next) {
	const {role_id,menu_id} = req.body
	try {
		
		const getRoleMenus = listSql(table2,{role_id,orderBy: 'role_id'},{hasPage: false})
		const menus = await getResult(getRoleMenus)
		const addMenusId = menu_id.filter(item => !menus.find(item2 => item2.menu_id === item))
		const delMenusId = menus.filter(item => !menu_id.includes(item.menu_id))	
		
		const muladddata = addMenusId.map(e=> {
			return {role_id,menu_id: e}
		})
		
		const muldeldata = delMenusId.map(e=> {
			return {role_id,menu_id: e.menu_id}
		})
		let addRoleMenuSql,delRoleMenuSql
		if (muladddata.length) {
			addRoleMenuSql = addSql(table2,muladddata)
			muladddata.length && await getResult(addRoleMenuSql)
		}
		if (muldeldata.length) {
			delRoleMenuSql = `delete from ${table2} where role_id = ${role_id} and menu_id ` + `in (${muldeldata.map(e => e.menu_id)})`
			muldeldata.length && await getResult(delRoleMenuSql)
		}
		res.json(req.app.locals.success('修改成功'))
	} catch (error) {
		res.json(req.app.locals.error(error))
	}
});

// 角色查询权限
router.get('/dataScope', async function(req,res,next) {
	const {role_id} = req.query
	
	const sql = listSql(table2,{role_id,orderBy:'role_id'})
	
	const rows = await getResult(sql)
	const menuIds = rows.map(e => e.menu_id)
	const valideMenusSql = `select * from ${table3} where menu_id in (${menuIds.join()})`
	const validRows = await getResult(valideMenusSql)
	// const getMenuSql = listSql(table3,{role_id},{hasPage: false})
	// const getMenuRows = await getResult(getMenuSql)
	res.json(req.app.locals.success(validRows.map(e => e.menu_id)))
})

export default router;